package com.example.application4.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.example.application4.R;
import com.example.application4.adapter.PhotoAdapter;
import com.example.application4.pojo.Photo;

import java.util.ArrayList;
import java.util.List;

public class PhotoActivity extends AppCompatActivity {

    private List<Photo> photoList = new ArrayList<>(); // 存储照片列表
    private static final int MY_PERMISSIONS_REQUEST_READ_MEDIA_IMAGES = 123; // 请求权限的请求码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this); // 全屏显示
        setContentView(R.layout.activity_photo); // 设置布局

        // 检查是否有读取媒体图像的权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES)
                != PackageManager.PERMISSION_GRANTED) {
            // 如果没有权限，请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_MEDIA_IMAGES},
                    MY_PERMISSIONS_REQUEST_READ_MEDIA_IMAGES);
        } else {
            // 如果已经有权限，加载照片
            loadPhotos();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_READ_MEDIA_IMAGES) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                loadPhotos();
            } else {
                showToast("没有权限读取图片");
            }
        }
    }

    private void loadPhotos() {
        initPhotoList();
        showPhotos();
    }

    private void showPhotos() {
        // 获取 RecyclerView 控件
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        // 设置 StaggeredGridLayoutManager ，3 列垂直排列
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        // 创建 PhotoAdapter 并设置给 RecyclerView
        PhotoAdapter adapter = new PhotoAdapter(this, photoList);
        recyclerView.setAdapter(adapter);
    }

    private void initPhotoList() {
        // 获取 ContentResolver
        ContentResolver contentResolver = getContentResolver();
        // 定义查询的 URI
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        // 定义选择条件，只选择 Pictures 文件夹下的图片
        String selection = MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " = ?";
        String[] selectionArgs = {"Pictures"};
        // 定义要查询的列
        String[] projection = {MediaStore.Images.Media.DATA};

        try (Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)) {
            if (cursor == null) {
                showToast("无法访问图片数据");
                return;
            }

            if (cursor.getCount() == 0) {
                showToast("请搜集些图片再来吧");
                return;
            }

            // 遍历查询结果，将图片路径添加到照片列表
            while (cursor.moveToNext()) {
                String imagePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                photoList.add(new Photo(imagePath));
            }
        } catch (Exception e) {
            showToast("加载图片时发生错误：" + e.getMessage());
        }
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}